﻿using System;
using System.Collections;
using System.Configuration;
using System.Web.UI.WebControls;
using CKEditor.NET;
using Telerik.Web.UI;
using Web_Oto.Business;
using Web_Oto.Common;
using Web_Oto.Data;

namespace Administration
{
    public partial class News : System.Web.UI.Page
    {
        private NewsBus _business;
        private string _imagePath = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            _business = new NewsBus();
            _imagePath = ConfigurationManager.AppSettings["newsPath"];

            if (!Page.IsPostBack)
            {
                hdfActiveSearch.Value = "0";
            }
        }

        protected void grid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            var newsId = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"].ToString();
            int id;
            int.TryParse(newsId, out id);

            var fileName = _business.GetFilePathById(id);
            CommonHelper.DeleteFile(_imagePath, fileName);

            var result = _business.Delete(id);
            if (result > 0)
            {
                msgBox.InnerHtml = "<p><strong>Xóa thành công</strong></p>";
                msgBox.Attributes["class"] = "msg msg-ok";
            }
            else
            {
                msgBox.InnerHtml = "<p><strong>Xóa không thành công</strong></p>";
                msgBox.Attributes["class"] = "msg msg-error";
            }
        }

        protected void grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            grid.DataSource = hdfActiveSearch.Value == "1" ? _business.GetAllNews(txtName.Text, txtIntro.Text) : _business.GetAllNews();
        }

        protected void grid_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            var gdItem = (e.Item as GridEditFormItem);
            var editableItem = ((GridEditableItem)e.Item);
            var values = new Hashtable();
            editableItem.ExtractValues(values);

            var news = new New
                           {
                               Id = (int) editableItem.GetDataKeyValue("Id"),
                               IsHot = (bool) values["IsHot"],
                               IsHomePage = (bool)values["IsHomePage"],
                               Date = Convert.ToDateTime(values["Date"])
                           };

            if (gdItem != null)
            {
                var editDescription = gdItem.FindControl("editDescription") as CKEditorControl;
                var uploader = gdItem.FindControl("uploadAvatar") as RadUpload;
                var hdfImage = ((HiddenField)gdItem.FindControl("hdfImage"));
                var editIntro = gdItem.FindControl("editIntro") as CKEditorControl;
                var txtSEO_Title = gdItem.FindControl("txtSEO_Title") as RadTextBox;
                var txtSEO_Keyword = gdItem.FindControl("txtSEO_Keyword") as RadTextBox;
                var txtSEO_Description = gdItem.FindControl("txtSEO_Description") as RadTextBox;
                var txtName = gdItem.FindControl("txtName") as RadTextBox;
                var txtTitleOfImage = gdItem.FindControl("txtTitleOfImage") as RadTextBox;

                if (editDescription != null && uploader != null && hdfImage != null
                    && editIntro != null && txtSEO_Title != null &&
                    txtSEO_Keyword != null && txtSEO_Description != null && txtName != null && txtTitleOfImage != null)
                {
                    if (uploader.UploadedFiles.Count > 0)
                    {
                        var oldPathImage = hdfImage.Value;
                        var avatar = uploader.UploadedFiles[0].FileName;
                        var filePath = CommonHelper.GetFilePath(_imagePath, ref avatar, oldPathImage);
                        uploader.UploadedFiles[0].SaveAs(Server.MapPath(filePath));
                        news.Image = avatar;
                    }

                    news.TitleOfImage = txtTitleOfImage.Text;
                    news.Name = txtName.Text;
                    news.Description = editDescription.Text;
                    news.Intro = editIntro.Text;
                    news.SEO_Title = txtSEO_Title.Text;
                    news.SEO_Keyword = txtSEO_Keyword.Text;
                    news.SEO_Description = txtSEO_Description.Text;

                    if (!CheckValidData(news.Name, news.Intro))
                        return;

                    var result = _business.Update(news);
                    if (result > 0)
                    {
                        msgBox.InnerHtml = "<p><strong>Cập nhật thành công</strong></p>";
                        msgBox.Attributes["class"] = "msg msg-ok";
                    }
                    else
                    {
                        msgBox.InnerHtml = "<p><strong>Cập nhật không thành công</strong></p>";
                        msgBox.Attributes["class"] = "msg msg-error";
                    }
                }
            }
        }

        protected void grid_InsertCommand(object sender, GridCommandEventArgs e)
        {
            var gdItem = (e.Item as GridEditFormItem);
            var editableItem = ((GridEditableItem)e.Item);
            var values = new Hashtable();
            editableItem.ExtractValues(values);

            var news = new New
            {   
                IsHot = (bool)values["IsHot"],
                IsHomePage = (bool)values["IsHomePage"],
                Date = Convert.ToDateTime(values["Date"])
            };

            if (gdItem != null)
            {
                var editDescription = gdItem.FindControl("editDescription") as CKEditorControl;
                var uploader = gdItem.FindControl("uploadAvatar") as RadUpload;
                var editIntro = gdItem.FindControl("editIntro") as CKEditorControl;
                var txtSEO_Title = gdItem.FindControl("txtSEO_Title") as RadTextBox;
                var txtSEO_Keyword = gdItem.FindControl("txtSEO_Keyword") as RadTextBox;
                var txtSEO_Description = gdItem.FindControl("txtSEO_Description") as RadTextBox;
                var txtName = gdItem.FindControl("txtName") as RadTextBox;
                var txtTitleOfImage = gdItem.FindControl("txtTitleOfImage") as RadTextBox;

                if (editDescription != null && uploader != null && editIntro != null && txtSEO_Title != null &&
                    txtSEO_Keyword != null && txtSEO_Description != null && txtName != null && txtTitleOfImage != null)
                {
                    if (uploader.UploadedFiles.Count > 0)
                    {
                        var avatar = uploader.UploadedFiles[0].FileName;
                        var filePath = CommonHelper.GetFilePath(_imagePath, ref avatar);
                        uploader.UploadedFiles[0].SaveAs(Server.MapPath(filePath));
                        //news.Image = filePath;
                        news.Image = avatar;
                    }

                    news.TitleOfImage = txtTitleOfImage.Text;
                    news.Name = txtName.Text;
                    news.Description = editDescription.Text;
                    news.Intro = editIntro.Text;
                    news.SEO_Title = txtSEO_Title.Text;
                    news.SEO_Keyword = txtSEO_Keyword.Text;
                    news.SEO_Description = txtSEO_Description.Text;

                    if(!CheckValidData(news.Name, news.Intro))
                        return;

                    var result = _business.Insert(news);
                    if (result > 0)
                    {
                        msgBox.InnerHtml = "<p><strong>Thêm mới thành công</strong></p>";
                        msgBox.Attributes["class"] = "msg msg-ok";
                    }
                    else
                    {
                        msgBox.InnerHtml = "<p><strong>Thêm mới không thành công</strong></p>";
                        msgBox.Attributes["class"] = "msg msg-error";
                    }
                }
            }
        }

        private bool CheckValidData(string name, string intro)
        {
            var result = true;
            var fielName = string.Empty;
            if (string.IsNullOrWhiteSpace(name))
            {
                fielName = fielName + " tiêu đề, ";
                result = false;
            }

            if (string.IsNullOrWhiteSpace(intro))
            {
                fielName = fielName + " giới thiệu, ";
                result = false;
            }

            if (!result)
            {
                fielName = fielName.TrimEnd(new[] { ',', ' ' });
                msgBox.InnerHtml = "<p><strong>Vui lòng nhập " + fielName + "</strong></p>";
                msgBox.Attributes["class"] = "msg msg-error";
            }

            return result;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            //Keep show status of box search.
            hdfActiveSearch.Value = "1";

            //Search product by name and category.
            grid.DataSource = _business.GetAllNews(txtName.Text, txtIntro.Text);
            grid.DataBind();
        }
    }
}